package com.example.petadopt.controller;

import com.example.petadopt.dao.UserDao;
import com.example.petadopt.entity.User;
import com.example.petadopt.dao.AdoptionApplicationDao;
import com.example.petadopt.entity.AdoptionApplication;
import com.example.petadopt.controller.vo.Result;
import  io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.SignatureAlgorithm;

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private AdoptionApplicationDao adoptionApplicationDao;

    @RequestMapping("/login")
    public ResponseEntity<Result> login(@RequestBody Map<String, String> loginInfo) {
        try {
            String account = loginInfo.get("account"); // 从请求体中获取用户名
            String pwd = loginInfo.get("pwd"); // 从请求体中获取密码
            User user = userDao.queryByAccountAndPwd(account, pwd);
            if (user == null) {
                return new ResponseEntity<>(new Result(4001, "账号或密码错误", null), HttpStatus.CREATED);
            } else {
                user.setPwd(null);
                // 制作JWT凭证
                Map<String, Object> claims = new HashMap<>();
                claims.put("user", user);

                String jwt = Jwts.builder()
                        .setClaims(claims)
                        .setSubject(user.getId() + "")
                        .setIssuedAt(new Date())
                        .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                        .signWith(SignatureAlgorithm.HS256, "123456")
                        .compact();

                Map<String, Object> data = new HashMap<>();
                data.put("user", user);
                data.put("jwttoken", jwt);
                return new ResponseEntity<>(new Result(2000, "登录成功", data), HttpStatus.OK);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(5000, "服务器内部错误", null), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("/reg")
    public ResponseEntity<Result> register(@RequestBody Map<String, String> regInfo) {
        try {
            String name = regInfo.get("name");
            String pwd = regInfo.get("pwd");
            String account = regInfo.get("account");
            String genderStr = regInfo.get("gender");
            String phone = regInfo.get("phone");
            String birthdate = regInfo.get("birthdate");

            if (userDao.existsByName(name)) {
                return new ResponseEntity<>(new Result(4002, "用户名已存在，请更改用户名", null), HttpStatus.CREATED);
            }

            if (userDao.existsByAccount(account)) {
                return new ResponseEntity<>(new Result(4002, "该账号已存在，请更改账号名", null), HttpStatus.CREATED);
            }

            int gender = 0;
            if ("男".equals(genderStr)) {
                gender = 1;
            } else if ("女".equals(genderStr)) {
                gender = 2;
            } else {
                return new ResponseEntity<>(new Result(4002, "无效的性别值", null), HttpStatus.BAD_REQUEST);
            }

            User newUser = new User();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = dateFormat.parse(birthdate);
                newUser.setBirth(birthdate);
            } catch (ParseException e) {
                return new ResponseEntity<>(new Result(4002, "无效的日期格式，请使用 YYYY-MM-DD 格式", null), HttpStatus.BAD_REQUEST);
            }

            newUser.setName(name);
            newUser.setPwd(pwd);
            newUser.setAccount(account);
            newUser.setPhone(phone);
            newUser.setSex(gender);

            userDao.save(newUser);

            return new ResponseEntity<>(new Result(2000, "注册成功", null), HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(5000, "服务器内部错误", null), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/personalcenter/info", method = RequestMethod.POST)
    public ResponseEntity<Result> getUserInfo(@RequestBody Map<String, String> userInfo) {
        try {
            // 从请求体中获取用户的唯一标识（例如用户ID）
            String userId = userInfo.get("id"); // 假设前端传递的是用户ID

            // 检查用户ID是否为空
            if (userId == null || userId.trim().isEmpty()) {
                return new ResponseEntity<>(new Result(4001, "用户ID不能为空", null), HttpStatus.BAD_REQUEST);
            }

            int id= Integer.parseInt(userId);
            // 根据用户ID从数据库中查询用户信息
            User user = userDao.queryById(id);
            if (user == null) {
                return new ResponseEntity<>(new Result(4003, "用户不存在", null), HttpStatus.NOT_FOUND);
            }

            // 将用户信息封装到返回的数据中
            Map<String, Object> data = new HashMap<>();
            data.put("username", user.getName());
            data.put("account", user.getAccount());
            data.put("gender", user.getSex() == 1 ? "男" : user.getSex() == 2 ? "女" : "未知");
            data.put("phone", user.getPhone());
            data.put("birthday", user.getBirth());

            return new ResponseEntity<>(new Result(2000, "查询成功", data), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(5000, "服务器内部错误", null), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public ResponseEntity<Result> applyForAdoption(@RequestBody Map<String, Object> applyInfo) {
        try {
            // 检查 'adoptUserId' 字段是否存在且不为 null
            Object adoptUserIdObj = applyInfo.get("adoptUserId");
            if (adoptUserIdObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adoptUserId' 字段", null), HttpStatus.BAD_REQUEST);
            }
            int userId = Integer.parseInt(adoptUserIdObj.toString());

            // 检查 'petId' 字段是否存在且不为 null
            Object petIdObj = applyInfo.get("petId");
            if (petIdObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'petId' 字段", null), HttpStatus.BAD_REQUEST);
            }
            int petId = Integer.parseInt(petIdObj.toString());

            // 检查其他字段是否存在且不为 null
            Object applicantNameObj = applyInfo.get("applicant_name");
            if (applicantNameObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'applicant_name' 字段", null), HttpStatus.BAD_REQUEST);
            }
            String applicantName = applicantNameObj.toString();

            Object adoptEmailObj = applyInfo.get("adopt_email");
            if (adoptEmailObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adopt_email' 字段", null), HttpStatus.BAD_REQUEST);
            }
            String adoptEmail = adoptEmailObj.toString();

            Object adoptPhoneObj = applyInfo.get("adopt_phone");
            if (adoptPhoneObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adopt_phone' 字段", null), HttpStatus.BAD_REQUEST);
            }
            String adoptPhone = adoptPhoneObj.toString();

            Object adoptAddressObj = applyInfo.get("adopt_address");
            if (adoptAddressObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adopt_address' 字段", null), HttpStatus.BAD_REQUEST);
            }
            String adoptAddress = adoptAddressObj.toString();

            Object adoptDateObj = applyInfo.get("adopt_date");
            if (adoptDateObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adopt_date' 字段", null), HttpStatus.BAD_REQUEST);
            }
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date adoptionDate = df.parse(adoptDateObj.toString());

            Object adoptReasonObj = applyInfo.get("adopt_reason");
            if (adoptReasonObj == null) {
                return new ResponseEntity<>(new Result(4002, "请求体中缺少 'adopt_reason' 字段", null), HttpStatus.BAD_REQUEST);
            }
            String adoptReason = adoptReasonObj.toString();

            AdoptionApplication application = new AdoptionApplication();
            application.setAdoptPetId(petId);
            application.setAdoptUserId(userId);
            application.setApplicantName(applicantName);
            application.setAdoptEmail(adoptEmail);
            application.setAdoptPhone(adoptPhone);
            application.setAdoptAddress(adoptAddress);
            application.setAdoptDate(adoptionDate);
            application.setAdoptReason(adoptReason);
            application.setStatusId(5);

            adoptionApplicationDao.save(application);

            return new ResponseEntity<>(new Result(2000, "申请提交成功", null), HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(5000, "服务器内部错误，请重试", null), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}